<template>
  <div class="table-filter-date-range-comp pad-rgt-10">
    <el-date-picker
      v-model="vModel"
      :type="type"
      :placeholder="placeholder"
      :format="destDisplayFormat"
      :value-format="destValueFormat"
      :picker-options="pickerOptions"
      size="small"
      @change="change">
    </el-date-picker>
  </div>
</template>

<script>

  export default {
    name: 'TableFilterDate',
    model: {
      event: 'change'
    },
    props: {
      value: {
        type: Array,
        default: () => {
          return [];
        }
      },
      type: {
        type: String,
        default: 'date'
      },
      displayFormat: {
        type: String,
        default: ''
      },
      valueFormat: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        vModel: '',
        placeholder: '',
        destDisplayFormat: '',
        destValueFormat: '',
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        }
      };
    },
    watch: {
      value: {
        handler(val = []) {
          this.vModel = val[0] || '';
        },
        immediate: true
      }
    },
    created() {
      this.initConfig();
    },
    methods: {
      initConfig() {
        switch (this.type) {
          case 'year':
            this.pickerOptions = [];
            this.destDisplayFormat = this.displayFormat || 'yyyy';
            this.destValueFormat = this.valueFormat || 'yyyy';
            break;
          case 'date':
            this.pickerOptions = [];
            this.destDisplayFormat = this.displayFormat || 'yyyy-MM-dd';
            this.destValueFormat = this.valueFormat || 'yyyy-MM-dd';
            break;
          default:
            break;
        }
      },
      change(val) {
        this.$emit('change', val ? [val] : []);
      },
      reset() {
        this.$emit('change', '');
      }
    }
  };
</script>

<style scoped>

</style>
